延續昨天的主題,今天要建立一個 Pipeline 元件,用來將爬到的資料存到 MongoDB 中。
在專案目錄的 pipelines.py 檔案中新增一個 MongoPipeline 類別:
import pymongo
class MongoPipeline(object):
    collection_name = 'article'
    def __init__(self, mongo_uri, mongo_db):
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db
    @classmethod
    def from_crawler(cls, crawler):
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
        )
    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]
    def close_spider(self, spider):
        self.client.close()
    def process_item(self, item, spider):
        self.db[self.collection_name].insert_one(dict(item))
        return item
其中這兩行代表從 Scrapy 設定中取得對應的參數值:
mongo_uri=crawler.settings.get('MONGO_URI'),
mongo_db=crawler.settings.get('MONGO_DATABASE', 'items')
同時要在專案目錄的 settings.py 檔案中加入這兩個設定:
MONGO_URI = 'mongodb://localhost:27017/'
MONGO_DATABASE = 'ithome2019'
最後要在 settings.py 檔案中把剛剛建立的 Pipeline 元件加入執行序列中,要注意指定的順序值要比昨天的 ithome_crawlers.pipelines.IthomeCrawlersPipeline 大,因為存進資料庫的應該是過濾後的結果。
ITEM_PIPELINES = {
    'ithome_crawlers.pipelines.IthomeCrawlersPipeline': 300,
    'ithome_crawlers.pipelines.MongoPipeline': 400,
}
最後執行 scrapy crawl ithome 指令來執行爬蟲,可以在啟動的 log 中看到元件已經被加入 Pipeline 中。
